package com.action.basic;

import java.util.List;

import com.action.common.Ajax;
import com.opensymphony.xwork2.ActionSupport;
import com.pojo.basic.ModuleTypes;
import com.service.basic.IModuleTypesService;
import com.vo.basic.ModuleTypesVo;

public class ModuleTypesAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private String root;
	private IModuleTypesService moduleTypesService;
	private Integer pid;
	private ModuleTypesVo  moduleTypesVo;
	
	//setter getter property
	
	public String getRoot() {
		return root;
	}

	
	public ModuleTypesVo getModuleTypesVo() {
		return moduleTypesVo;
	}


	public void setModuleTypesVo(ModuleTypesVo moduleTypesVo) {
		this.moduleTypesVo = moduleTypesVo;
	}


	public Integer getPid() {
		return pid;
	}

	public void setPid(Integer pid) {
		this.pid = pid;
	}

	public void setRoot(String root) {
		this.root = root;
	}
	
	public void setModuleTypesService(IModuleTypesService moduleTypesService) {
		this.moduleTypesService = moduleTypesService;
	}
	
	//action method
	
	public void savaModuleTypes(){
		Integer id = (Integer) moduleTypesService.addModuleTypes(moduleTypesVo);
		String info = "";
		if(id == -1){
			info = "{success:false,info:'添加失敗'}";
		}else{
			info = "{success:true,info:'添加成功'}";
		}
		Ajax.sendMsg(info);
	}
	
	public String findRootChildModuleTypes(){
		List<ModuleTypes> temps = moduleTypesService.findChildModuleTypes(this.getPid());
		this.setRoot(this.spanListToExtTreeData(temps));
		return SUCCESS;
	}
	
	public void findChildModuleTypes(){
		List<ModuleTypes> temps = moduleTypesService.findChildModuleTypes(this.getPid());
		Ajax.sendMsg(this.spanListToExtTreeDataByAjax(temps));
	}
	
	public String spanListToExtTreeData(List<ModuleTypes> moduleTypes){
		String datas = "";
		if(moduleTypes!=null&&moduleTypes.size()>0){
			for(ModuleTypes  mt: moduleTypes){
				String flag = mt.getUrl().equals("#")?"false":"true";
				String href = mt.getUrl().equals("#")?"":"";
				datas = datas + "{id:'"+mt.getId()+"',text:'"+mt.getName()+"',href:'"+href+"',checked:false,leaf:"+flag+"},";
			}
			datas = datas.substring(0,datas.length()-1);
		}
		return datas;
	}
	
	public String spanListToExtTreeDataByAjax(List<ModuleTypes> moduleTypes){
		StringBuffer sb = new StringBuffer("[");
		int count = 0;
		if(moduleTypes!=null&&moduleTypes.size()>0){
			for(ModuleTypes  mt: moduleTypes){
				String flag = mt.getUrl().equals("#")?"true":"false";
				String href = mt.getUrl().equals("#")?"":"";
				sb.append("{id:'"+mt.getId()+"',text:'"+mt.getName()+"',href:'"+href+"',checked:false,leaf:"+flag+"},");
			}
			if (count < moduleTypes.size() - 1) {
				sb.append(",");
			}
			count++;
		}
		sb.append("]");
		return sb.toString();
	}

}
